<?php
class Clu_Service_Widget
{
	public $db;
	public $v;
	
	public function __construct()
	{
		$this->db = Zend_Db_Table::getDefaultAdapter();
	}
	
	public function getTemplate($siteName, $request)
	{
		$sql = sprintf("select * from `request_templates` where site='%s' and request='%s'", $siteName, $request);
//		$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
		$result = $this->db->fetchRow($sql);
		if ($result)
			return $result['template'];
		else
		{
			return 'page';
		}			
	}
	/*
	 * @param: $params 'site', 'master_request', 'theme', 'template'
	 */
	public function getWidgetsInfo($params)
	{
		//either matching 
		// 1. (site, theme, template, request , (presence_identifier))
		// Because this 2. is newly added as of 2009.11.01 
		// 2. or (site, theme, template, request + presence_identifer = -2 ) <-- across request
		
		// 3. or (site, theme, template + (presence_identifier = 0)) <--across template
		// 4. or (site, theme + (presence_identifer = -1 ) <-- across theme
		
		$sql = sprintf("select * from `widget_positions` where 
				(site='%s' AND theme='%s' AND template='%s'	AND master_request='%s' 
					AND presence_identifier='%s')
				OR (site='%s' AND theme='%s' AND template='%s'	AND master_request='%s' 
					AND presence_identifier='-2')
				OR (site='%s' AND theme='%s' AND template='%s'
					AND presence_identifier='0')
				OR (site='%s' AND theme='%s' 
					AND presence_identifier='-1')",
				 $params['site'], $params['theme'],	 $params['template'], $params['master_request'],
				 	$params['presence_identifier'],
				 $params['site'], $params['theme'],	 $params['template'], $params['master_request'],
				 $params['site'], $params['theme'],	 $params['template'],
				 $params['site'], $params['theme']	 
				 );
//				 die($sql);
//		$this->db->setFetchMode(Zend_Db::FETCH_ASSOC); by default
		$result = $this->db->fetchAll($sql);
//		die_a($result);
		return $result;
	}
	
	public function renderToHolder($viewParams, $script, $region, $weight)
	{
    	$name = 'region' . $region . '_box';
    	
        $placeHolder = $name.$weight;
//        echo $placeHolder . "<br/>";
        $holderWeights = Zend_Registry::get('holderWeights');
        if (array_key_exists($placeHolder, $holderWeights))
        {
        	return false;
        }	
    	$layout = Zend_Layout::getMvcInstance();
    	$view = $layout->getView();
    	$view->viewParams = $viewParams;
        $view->placeholder($placeHolder)->captureStart();
        echo $view->render($script);
        $view->placeholder($placeHolder)->captureEnd();
        $holderWeights[$placeHolder] = $weight; 
        Zend_Registry::set('holderWeights', $holderWeights);
        return true;
	}

	/*
	public function setHolder($content, $region, $weight)
	{
		$name = 'region' . $region . '_box';
        $placeHolder = $name.$weight;
        $holderWeights = Zend_Registry::get('holderWeights');
        if (array_key_exists($placeHolder, $holderWeights))
        {
            return false;
        }
        $view->placeholder($placeHolder)->captureStart();
        echo $content;
        $view->placeholder($placeHolder)->captureEnd();
        $holderWeights[$placeHolder] = $weight; 
        Zend_Registry::set('holderWeights', $holderWeights);
        return true;
	}
	*/
	
	/*
	public function getWidgetsInfo($masterWidgetInfo)
	{
		$sql = "select * from `widget_positions` where 1 ";
		$params = array('site', 'master_request', 'theme','template');
		foreach ($params as $key)
		{
			$sql = $sql . sprintf(" AND $key='%s'", $masterWidgetInfo[$key]);
		}
//		$this->db->setFetchMode(Zend_Db::FETCH_ASSOC); by default
		$result = $this->db->fetchAll($sql);
		return $result;
	}
	*/
	

    public function convertDashedNameToCamelName($dashedName)
    {
    	//convert names like test-master to testMaster
    	$len = strlen($dashedName);
    	$ret = '';
    	for ($i=0; $i < $len; $i ++)
    	{
    		if (($dashedName[$i] == '-') && ($i+1 < $len) )
    		{
    			$ret = $ret . strtoupper($dashedName[$i+1]);
    			$i = $i + 1;
    		}
    		else
    		{
    			$ret = $ret. $dashedName[$i];
    		}
    	}
    	return $ret;
    }
    
    public function addWidget($widget, $params)
    {
		$tmp = explode('/', $widget['widget_request']);
		$nodeTypes = explode(" ",Zend_Registry::get('configuration')->nodeTypes);
    	if(in_array($tmp[0], $nodeTypes ) && $tmp[0] != 'gallery')
    		$tmp[0] = 'node';
    	$controllerClassName = Ucwords($tmp[0]) . '_' . Ucwords($tmp[1]) . 'Controller';
    	require_once (APP_PATH.'/modules/'.$tmp[0] . '/controllers/' . Ucwords($tmp[1]) . 'Controller.php');
       	$widgetController = new $controllerClassName($widget, $params);
       	$action = $this->convertDashedNameToCamelName($tmp[2]);
    	$a = $action . "Action";
    	$widgetController->{$a}();
    	if (isset($widget['clu_no_layout']))
    	{
    		//render and echo right away. No layout
    		$widgetController->renderNoHolderAndReturn();
    	}
    	else
    	{
    		$widgetController->renderToHolder();
    	}
    	
    	//TODO: destroy the object $widgetController here
		unset($widgetController);
    }
	
    /*
     * TODO: This function is currently not used
     */

    public function setupViewNoLayout()
	{
		echo "setupView No Layout <br/>";
		$this->v = new Zend_View();
        $this->v->setEncoding('UTF-8');
        $this->v->doctype('XHTML1_STRICT');
        $this->v->addHelperPath(
            APP_PATH . '/library/Clu/View/Helper',
            'Clu_View_Helper'
        );
        $this->v->setScriptPath(APP_PATH . '/');
	}
	public function getView()
	{
//		return $this->v;
    	$layout = Zend_Layout::getMvcInstance();
    	$view = $layout->getView();
    	return $view;
	}
	
	public function setupLayout($template, $theme)
	{
		//echo "setingup layout <br/>";
	    $view = new Zend_View;
        $view->setEncoding('UTF-8');
        $view->doctype('XHTML1_STRICT');
        $view->addHelperPath(
            APP_PATH . '/library/Clu/View/Helper',
            'Clu_View_Helper'
        );
        $view->setScriptPath(APP_PATH . '/');
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view);
        $viewRenderer->setNeverRender();
        
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);	
        Zend_Layout::startMvc();
//        die('abc');
        //Zend_Registry::set('cluView', $view);
        //set place holders Weight
        $layout = Zend_Layout::getMvcInstance();
    	$layout->setLayoutPath( APP_PATH . '/public/themes/'.$theme.'/layouts/scripts');
	    $layout->setLayout ($template); //common.phtml
	    //reset 'holderWeights'
        Zend_Registry::set('holderWeights', array());
	}
    

}
?>
